<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Gotcha\App\Extensions;

// Gotcha security extension class

use Gotcha\App\Types\Arrays;
use Gotcha\App\Types\Int;
use Gotcha\App\Types\String;

class SecurityExtension {
    private function generateFormValidationToken() {
        return new String(uniqid('Gotcha', true));
    }

    public function returnFormValidationToken() {
        $generatedToken = $this->generateFormValidationToken();
        $currentTime = new String(time()); // Current time in seconds

        // We save currently created token to the file
        file_put_contents(GOTCHA_ROOT_DIR.'\\App\Security\Tokens\__form.txt', $generatedToken.'|'.$currentTime.PHP_EOL, LOCK_EX | FILE_APPEND);

        return $generatedToken;
    }

    public function checkSavedFormTokens() {
        $tokenLifetime = new Int(FileSystemExtension::returnConfigValue(new String('tokenlifetime')));
        $currentTime = new Int(time());
        $newContent = new String(''); // We store valid tokens in this variable

        // For each element in tokens' file we compare
        // current time and time when token was saved.
        // If $tokenLifetime < $currentTime - $timeWhenTokenWasSaved
        // we delete that token.
        $file = file_get_contents(GOTCHA_ROOT_DIR.'\\App\Security\Tokens\__form.txt');
        if(!$file && !strlen($file) == 0) {
            ErrorsExtension::throwErrorAndSaveLog(new String('CANNOT_READ_TOKENS_FILE'), new Arrays(array(GOTCHA_ROOT_DIR.'\\App\Security\Tokens\__form.txt')));
        }

        // Properly opened file, let's read it.
        $fileLines = explode(PHP_EOL, $file);
        array_pop($fileLines);

        foreach($fileLines as $line) {
            $fileLine = explode('|', $line);
            if($currentTime->int - $fileLine[1] <= $tokenLifetime->int) {
                $newContent .= $line.PHP_EOL;
            }
        }

        // Rewrite tokens' file
        file_put_contents(GOTCHA_ROOT_DIR.'\\App\Security\Tokens\__form.txt', $newContent, LOCK_EX);
    }
}